/*
 * @Description:
 * @Author: HYH
 * @LastEditors: HYH
 * @LastEditTime: 2023-02-10 17:27:41
 */
/** */
export const useCanvas = () => {
  return { imgToBase64 }
}

/**图片转base64 */
const imgToBase64 = (imgSrc: string) => {
  return new Promise((resolve, reject) => {
    const image = new Image()
    image.crossOrigin = ''
    image.src = imgSrc
    image.onload = function () {
      const canvas = document.createElement('canvas')
      canvas.width = image.width
      canvas.height = image.height
      const ctx = canvas.getContext('2d')
      ctx!.drawImage(image, 0, 0, image.width, image.height)
      let ext = image.src.substring(image.src.lastIndexOf('.') + 1).toLowerCase()
      if (ext === 'jpg') {
        ext = 'jpeg' //这个地方是由于如果是jpg, 他会识别成image/png
      }
      const dataURL = canvas.toDataURL('image/' + ext)
      resolve(dataURL)
    }
  })
}
